#!/bin/bash
#
# 12-aegis-docker-status - the docker status of the MOTD.
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Aegis can be found at:
# https://github.com/seatonjiang/aegis
#
# Copyright (C) 2021-2022 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

export LC_ALL=C.UTF-8

set -u -o pipefail

# Colors
G="\033[01;32m"
R="\033[01;31m"
N="\033[0m"

if type docker >/dev/null 2>&1; then
    mapfile -t containers < <(docker ps --format '{{.Names}}\t{{.Status}}' | sort -k1 | awk '{ print $1,$2 }')

    OUTPUT=""
    for i in "${!containers[@]}"; do
        IFS=" " read -r NAME STATUS <<< "${containers[i]}"

        # Green if the service is active, red otherwise
        if [[ "${STATUS}" == "Up" ]]; then
            OUTPUT+="${NAME}:,${G}${STATUS,,}${N},"
        else
            OUTPUT+="${NAME}:,${R}${STATUS,,}${N},"
        fi

        # Insert \n every 3 columns
        if [ $((("$i"+1) % 3)) -eq 0 ]; then
            OUTPUT+="\n"
        fi
    done
    OUTPUT+="\n"

    echo -e "  [Docker Status]\n"
    echo -ne "${OUTPUT}" | column -ts $',' | sed -e 's/^/  /'
    echo
fi
